package com.yy.finvideoplayer.videoview

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import android.view.View

class Indicator : View {

    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    )

    private val progressPaint = Paint().apply {
        color = Color.WHITE
        style = Paint.Style.FILL
        isAntiAlias = true
    }
    private val backgroundPaint = Paint().apply {
        color = Color.DKGRAY
        style = Paint.Style.FILL
        isAntiAlias = true
    }

    private var progress = 0
    private var max = 0

    private val density = context.resources.displayMetrics.density

    private var rectWidth = 0F
    private var rectHeight = density * 4
    private var gap = density * 2
    private var radius = gap

    private val rectList = ArrayList<RectF>()

    private val shouldDraw: Boolean
        get() = max > 0

    fun setMax(newMax: Int) {
        if (this.max == newMax) {
            return
        }

        if (this.max > newMax) {
            while (rectList.size > newMax) {
                rectList.removeAt(0)
            }
        } else {
            for (i in this.max until newMax) {
                rectList.add(RectF())
            }
        }

        this.max = newMax
        requestLayout()
    }

    fun setProgress(progress: Int) {
        this.progress = progress
        invalidate()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        rectWidth = (measuredWidth - (max - 1) * gap) / max
        rectList.forEachIndexed { index, rectF ->
            val l = index * (rectWidth + gap)
            val t = 0F
            val r = l + rectWidth
            val b = t + rectHeight
            rectF.set(l, t, r, b)
        }
    }

    override fun onDraw(canvas: Canvas) {
        if (!shouldDraw) {
            return
        }
        rectList.forEachIndexed { index, rectF ->
            canvas.drawRoundRect(
                rectF, radius, radius,
                if (index < progress) {
                    progressPaint
                } else {
                    backgroundPaint
                }
            )
        }
    }
}